<template>
    <div id="chat-box">
        <nav-bar class="nav-bar">
            <div slot="left" class="back" @click="backClick">
               <img src="~assets/img/common/back.svg" alt="">
            </div>
            <div slot="center">欢迎来到{{scenic.name}}咨询室({{count}})</div>
        </nav-bar>
        <div class="msg-box" ref="msgBox">
            <div v-for="(i,index) in list" :key="index" class="msg" :style="i.username === username?'flex-direction:row-reverse':'flex-direction:row'">
                <div class="user-head">
                    <img src="~assets/img/common/placeholder.png" alt="i.username">
                </div>
                <div class="user-msg">
                    <span :style="i.username == username?'float: right;':''" :class="i.username == username?'right':'left'">{{i.content}}</span>
                </div>
            </div>
        </div>
        <div class="input-box">
            <input type="text" ref="sendMsg" v-model="contentText" @keyup.enter="sendText()" />
            <div class="btn" :class="{['btn-active']:contentText}" @click="sendText()">发送</div>
        </div>
    </div>
</template>
<script>
import NavBar from 'components/common/navbar/NavBar'

import {getDetail} from 'network/detail.js'
export default {
    name: 'Chat',
    data() {
        return {
            ws: null, // websocket对象
            username: "", // 当前用户名称
            userId: "", // 当前用户ID
            scenic: {},
            // avatar: '', // 当前用户头像，暂不支持自定义上传头像，留作日后开发
            scenicIid: "",
            count: 0,
            // list: [{'userId':'5761375254556672','username':"请喊我文刀",'content':"你好啊"},
            // {'userId':"1234" ,'username':"请",'content':"好个锤子"},
            // {'userId':'5761375254556672','username':"请喊我文刀",'content':"能不能好好说话"},
            // {'userId':"1234" ,'username':"请",'content':"说尼玛"},
            // {'userId':'5761375254556672','username':"请喊我文刀",'content':"曹尼玛，你个傻逼"},
            // {'userId':"1234" ,'username':"请",'content':"骂你了怎么着"},
            // {'userId':'5761375254556672','username':"请喊我文刀",'content':"你个楞逼"},
            // {'userId':"1234" ,'username':"请",'content':"妈的智障"}], // 聊天记录的数组
            list: [], // 聊天记录的数组
            contentText: "", // input输入的值
        }
    },
    components: {
        NavBar,
    },
    mounted() {
      this.initWebSocket();
      this._getDetail();
    },
    destroyed() {
      // 离开页面时关闭websocket连接
      this.ws.onclose();
    },
    methods: {
        sendText() {
            if(this.contentText === "") {
                this.$toast.show("输入的内容不能为空",1000);
            }else {
                let _this = this;
                // 点击按钮会导致输入框失去焦点，所以在这重新获取焦点
                _this.$refs.sendMsg.focus();
                let params = {
                  userId: _this.userId,
                  username: _this.username,
                  // avatar: _this.avatar,
                  msg: _this.contentText,
                  count: _this.count
                };
                _this.ws.send(JSON.stringify(params)); //调用WebSocket send()发送信息的方法
                _this.contentText = "";
                setTimeout(() => {
                  _this.scrollBottm();
                }, 500);
            }
        },
        // 进入页面创建websocket连接
        initWebSocket() {
          //先保存当前vue对象，方便后续使用
          let _this = this;
          _this.scenicIid = _this.$route.params.id;
          _this.userId = _this.$store.state.user[0].id;
          _this.username = _this.$store.state.user[0].username;
          // 判断页面有没有存在websocket连接
          if (window.WebSocket) {
            var url = 'ws://localhost:9988/serviceChat/' +_this.scenicIid + '/' + _this.userId;
            let ws = new WebSocket(url);
            _this.ws = ws;
            ws.onopen = function() {
              console.log("服务器连接成功: " + url);
            };
            ws.onclose = function() {
              console.log("服务器连接关闭: " + url);
            };
            ws.onerror = function() {
              console.log("服务器连接出错: " + url);
            };
            ws.onmessage = function(evt) {
              //接收服务器返回的数据
              let resData = JSON.parse(evt.data);
              console.info(resData);
              _this.count = resData.count;
              _this.list = [
                ..._this.list,
                { userId: resData.userId, username: resData.username, content: resData.msg}
              ];
            };
          }
        },
        // 滚动条到底部
        scrollBottm() {
            let el = this.$refs.msgBox;
            el.scrollTop = el.scrollHeight;
        },
        backClick() {
            this.$router.go(-1);
        },
        _getDetail() {
          getDetail(this.scenicIid).then((res) => {
            console.info(res);
            this.scenic = res.data.baseData;
          })
        }
    },
}
</script>
<style>
    .back img{
        margin-top: 13px;
    }
    .nav-bar {
        position: relative;
        z-index: 9;
        background-color: greenyellow;
    }
    .btn {
    height: 2.3rem;
    min-width: 4rem;
    background: #e0e0e0;
    padding: 0.5rem;
    font-size: 0.88rem;
    color: white;
    text-align: center;
    border-radius: 0.2rem;
    margin-left: 0.5rem;
    transition: 0.5s;
  }
  .btn-active {
    background: #409eff;
  }
  input {
    height: 2.3rem;
    display: inline-block;
    width: 100%;
    padding: 0.5rem;
    border: none;
    border-radius: 0.2rem;
    font-size: 0.88rem;
  }
  .input-box {
    padding: 0 0.5rem;
    position: absolute;
    bottom: 44px;
    width: 100%;
    height: 3.5rem;
    background: #fafafa;
    box-shadow: 0 0 5px #ccc;
    display: flex;
    justify-content: space-between;
    align-items: center; 
  }
  @keyframes toLeft {
    0% {
      opacity: 0;
      transform: translateX(-10px);
    }
    100% {
      opacity: 1;
      transform: translateX(0px);
    }
  }
  @keyframes toright {
    0% {
      opacity: 0;
      transform: translateX(10px);
    }
    100% {
      opacity: 1;
      transform: translateX(0px);
    }
  }
  .left {
    background: greenyellow;
    color: white;
    animation: toLeft 0.5s ease both 1;
  }
  .right {
    background: #53a8ff;
    color: white;
    animation: toright 0.5s ease both 1;
  }
  span {
    display: inline-block;
    padding: 0.5rem 0.7rem;
    border-radius: 0.5rem;
    margin-top: 0.2rem;
    font-size: 0.88rem;
  }
  .user-msg {
    width: 80%;
   position: absolute;
    word-break: break-all;
    position: relative;
    z-index: 5;
  }
  .msg-box {
    position: absolute;
    height: calc(100% - 6.5rem - 100px);
    width: 100%;
    margin-top: 3rem;
    overflow-y: scroll;
  }
  .msg {
    width: 95%;
    min-height: 2.5rem;
    margin: 1rem 0.5rem;
    position: relative;
    display: flex;
    justify-content: flex-start !important;
  }
  .chat-box {
    margin: 0 auto;
    background: #fafafa;
    position: absolute;
    height: 100%;
    width: 100%;
    max-width: 700px;
  }
  .user-head {
    min-width: 2.5rem;
    width: 20%;
    width: 2.5rem;
    height: 2.5rem;
    border-radius: 50%;
    background: #f1f1f1;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .user-head img {
    width: 42px;
    height: 42px;
    border-radius: 50%;
  }
</style>